const API_BASE_URL = '/api'

// 通用API请求函数
export async function apiRequest<T>(
  endpoint: string, 
  options: RequestInit = {}
): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`
  
  // 获取JWT令牌
  const token = localStorage.getItem('auth_token')
  
  const defaultOptions: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
      ...(token && { 'Authorization': `Bearer ${token}` }),
      ...options.headers,
    },
    ...options,
  }

  try {
    const response = await fetch(url, defaultOptions)
    
    if (!response.ok) {
      throw new Error(`API请求失败: ${response.status} ${response.statusText}`)
    }
    
    return await response.json()
  } catch (error) {
    console.error('API请求错误:', error)
    throw error
  }
}

// AI相关API接口
export const aiAPI = {
  // 智能解析自然语言输入
  async smartParse(text: string) {
    return apiRequest<{
      success: boolean
      result?: any
      message: string
      warning?: string
    }>('/ai/smart-parse', {
      method: 'POST',
      body: JSON.stringify({ text })
    })
  },

  // 任务分解
  async decomposeTask(title: string, description?: string) {
    return apiRequest<{
      success: boolean
      subtasks?: Array<{
        title: string
        completed: boolean
      }>
      message: string
      fallback?: any
    }>('/ai/decompose', {
      method: 'POST',
      body: JSON.stringify({ title, description })
    })
  },

  // 获取智能建议（基础建议，无需用户态）
  async getSuggestions() {
    // 获取基础建议
    return apiRequest<{
        success: boolean
        suggestions?: Array<{
          id: string
          type: string
          message: string
          actions: Array<{
            label: string
            action: string
            primary: boolean
          }>
          taskId?: string
          reasoning?: string
          createdAt: string
        }>
        message: string
        error?: string
        fallback?: any
      }>('/ai/suggestions', {
        method: 'GET'
      })
  },

  // 智能搜索
  async search(query: string) {
    return apiRequest<{
      success: boolean
      searchType?: string
      intent?: string
      suggestions?: string[]
      relatedTasks?: string[]
      searchTips?: string[]
      message: string
      error?: string
      fallback?: any
    }>('/ai/search', {
      method: 'POST',
      body: JSON.stringify({ query })
    })
  },

  // 获取个性化建议（支持模式与任务上下文）
  async getPersonalizedSuggestions(
    context: string,
    options?: { mode?: 'dashboard' | 'task'; taskId?: string }
  ) {
    return apiRequest<{
      success: boolean
      suggestions?: Array<{
        id: string
        type: string
        message: string
        actions: Array<{
          label: string
          action: string
          primary: boolean
        }>
        taskId?: string
        reasoning?: string
        createdAt: string
      }>
      message: string
      error?: string
      fallback?: any
    }>('/ai/personalized-suggestions', {
      method: 'POST',
      body: JSON.stringify({ context, ...(options || {}) })
    })
  },

  // 记录建议反馈
  async recordSuggestionFeedback(suggestionId: string, action: string, rating: number, feedbackText: string) {
    return apiRequest<{
      success: boolean
      message: string
    }>('/ai/suggestion-feedback', {
      method: 'POST',
      body: JSON.stringify({
        suggestionId,
        action,
        rating,
        feedbackText
      })
    })
  },

  // 智能解析动作参数
  async parseActionParameters(suggestion: any, action: string, taskContext?: any) {
    return apiRequest<{
      success: boolean
      result?: {
        action: string
        parameters: {
          dueDate?: string
          priority?: string
          status?: string
          category?: string
          reminderMinutes?: number
          notes?: string
        }
        reasoning: string
        confidence: number
        requiresUserInput: boolean
        userPrompt?: string
      }
      message: string
      warning?: string
    }>('/ai/parse-action-parameters', {
      method: 'POST',
      body: JSON.stringify({ suggestion, action, taskContext })
    })
  },

  // 批量解析动作参数
  async batchParseActions(suggestions: any[], taskContext?: any) {
    return apiRequest<{
      success: boolean
      results: Array<{
        suggestionId: string
        action: string
        success: boolean
        result?: any
        error?: string
      }>
      message: string
    }>('/ai/batch-parse-actions', {
      method: 'POST',
      body: JSON.stringify({ suggestions, taskContext })
    })
  }
}

// 任务相关API接口
export const taskAPI = {
  // 获取所有任务
  async getAllTasks() {
    return apiRequest<Array<{
      id: string
      title: string
      description?: string
      dueDate?: string
      priority: string
      category: string
      tags: string[]
      completed: boolean
      notes?: string
      createdAt: string
      updatedAt: string
    }>>('/tasks', {
      method: 'GET'
    })
  },

  // 创建任务
  async createTask(taskData: {
    title: string
    description?: string
    dueDate?: string
    priority: string
    category: string
    tags?: string[]
    notes?: string
  }) {
    return apiRequest<{
      id: string
      message: string
    }>('/tasks', {
      method: 'POST',
      body: JSON.stringify(taskData)
    })
  },

  // 更新任务
  async updateTask(taskId: string, updates: Partial<{
    title: string
    description: string
    dueDate: string
    reminderMinutes: number
    priority: string
    category: string
    tags: string[]
    completed: boolean
    notes: string
    status: string
  }>) {
    return apiRequest<{
      message: string
    }>(`/tasks/${taskId}`, {
      method: 'PUT',
      body: JSON.stringify(updates)
    })
  },

  // 切换任务完成状态
  async toggleTask(taskId: string) {
    return apiRequest<{
      message: string
    }>(`/tasks/${taskId}/toggle`, {
      method: 'PATCH'
    })
  },

  // 删除任务
  async deleteTask(taskId: string) {
    return apiRequest<{
      message: string
    }>(`/tasks/${taskId}`, {
      method: 'DELETE'
    })
  },

  // ========== 子任务管理 API ==========
  
  // 获取任务的所有子任务
  async getSubtasks(taskId: string) {
    return apiRequest<Array<{
      id: string
      task_id: string
      title: string
      completed: boolean
    }>>(`/tasks/${taskId}/subtasks`, {
      method: 'GET'
    })
  },

  // 创建新子任务
  async createSubtask(taskId: string, title: string) {
    return apiRequest<{
      id: string
      task_id: string
      title: string
      completed: boolean
      message: string
    }>(`/tasks/${taskId}/subtasks`, {
      method: 'POST',
      body: JSON.stringify({ title })
    })
  },

  // 更新子任务
  async updateSubtask(subtaskId: string, data: { title: string, completed?: boolean }) {
    return apiRequest<{
      message: string
    }>(`/tasks/subtasks/${subtaskId}`, {
      method: 'PUT',
      body: JSON.stringify(data)
    })
  },

  // 切换子任务完成状态
  async toggleSubtask(subtaskId: string) {
    return apiRequest<{
      message: string
    }>(`/tasks/subtasks/${subtaskId}/toggle`, {
      method: 'PATCH'
    })
  },

  // 删除子任务
  async deleteSubtask(subtaskId: string) {
    return apiRequest<{
      message: string
    }>(`/tasks/subtasks/${subtaskId}`, {
      method: 'DELETE'
    })
  }
}

// 统计相关API接口
export const statsAPI = {
  // 获取统计概览
  async getOverview() {
    return apiRequest<{
      success: boolean
      data: {
        totalTasks: number
        completedTasks: number
        pendingTasks: number
        overdueTasks: number
        completionRate: number
        overdueRate: number
      }
    }>('/stats/overview')
  },

  // 获取分类分布
  async getCategoryDistribution() {
    return apiRequest<{
      success: boolean
      data: Array<{
        category: string
        total: number
        completed: number
        pending: number
        completionRate: number
      }>
    }>('/stats/category-distribution')
  },

  // 获取优先级分布
  async getPriorityDistribution() {
    return apiRequest<{
      success: boolean
      data: Array<{
        priority: string
        total: number
        completed: number
        pending: number
        completionRate: number
      }>
    }>('/stats/priority-distribution')
  },

  // 获取时间趋势
  async getTimeTrends(days: number = 7) {
    return apiRequest<{
      success: boolean
      data: {
        period: string
        trends: Array<{
          date: string
          created: number
          completed: number
        }>
      }
    }>(`/stats/time-trends?days=${days}`)
  },

  // 获取效率分析
  async getEfficiency() {
    return apiRequest<{
      success: boolean
      data: {
        avgCompletionDays: number
        delayRate: number
        categoryEfficiency: Array<{
          category: string
          avgDays: number
          completedCount: number
        }>
        totalCompletedTasks: number
      }
    }>('/stats/efficiency')
  },

  // 获取标签使用统计
  async getTagUsage() {
    return apiRequest<{
      success: boolean
      data: Array<{
        tag: string
        count: number
      }>
    }>('/stats/tag-usage')
  },

  // 获取连续完成天数
  async getStreak() {
    return apiRequest<{
      success: boolean
      data: {
        currentStreak: number
        maxStreak: number
        totalCompletedDays: number
      }
    }>('/stats/streak')
  }
}

// 导出API
export const exportAPI = {
  // 导出任务数据
  async exportTasks(format: 'json' | 'csv' = 'json') {
    return apiRequest<any>(`/export/tasks?format=${format}`)
  },

  // 导出统计数据
  async exportStats() {
    return apiRequest<any>('/export/stats')
  },

  // 导出重复任务
  async exportRecurring() {
    return apiRequest<any>('/export/recurring')
  }
}

// 重复任务API
export const recurringAPI = {
  // 获取所有重复任务
  async getAllRecurringTasks() {
    return apiRequest<any[]>('/recurring')
  },

  // 获取重复任务详情
  async getRecurringTask(id: string) {
    return apiRequest<any>(`/recurring/${id}`)
  },

  // 创建重复任务
  async createRecurringTask(data: {
    title: string
    description?: string
    priority?: string
    category?: string
    tags?: string[]
    notes?: string
    recurringType: 'daily' | 'weekly' | 'monthly' | 'yearly'
    recurringPattern?: string
    userId?: string
  }) {
    return apiRequest<{ id: string; message: string }>('/recurring', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  },

  // 更新重复任务
  async updateRecurringTask(id: string, data: any) {
    return apiRequest<any>(`/recurring/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data)
    })
  },

  // 暂停重复任务
  async pauseRecurringTask(id: string) {
    return apiRequest<{ message: string }>(`/recurring/${id}/pause`, {
      method: 'PATCH'
    })
  },

  // 恢复重复任务
  async resumeRecurringTask(id: string) {
    return apiRequest<{ message: string }>(`/recurring/${id}/resume`, {
      method: 'PATCH'
    })
  },

  // 生成任务实例
  async generateInstances(id: string) {
    return apiRequest<{ message: string; generatedTaskIds: string[]; count: number }>(`/recurring/${id}/generate`, {
      method: 'POST'
    })
  },

  // 删除重复任务
  async deleteRecurringTask(id: string) {
    return apiRequest<{ message: string }>(`/recurring/${id}`, {
      method: 'DELETE'
    })
  },

  // 获取统计数据
  async getStats() {
    return apiRequest<{
      totalRecurringTasks: number
      activeRecurringTasks: number
      totalInstances: number
      upcomingInstances: number
    }>('/recurring/stats/overview')
  },

  // 触发处理
  async triggerProcessing() {
    return apiRequest<{ message: string }>('/recurring/trigger-processing', {
      method: 'POST'
    })
  },

  // 清理过期实例
  async cleanupOldInstances(daysToKeep: number = 30) {
    return apiRequest<{ message: string }>('/recurring/cleanup', {
      method: 'POST',
      body: JSON.stringify({ daysToKeep })
    })
  }
}

export default {
  ai: aiAPI,
  task: taskAPI,
  stats: statsAPI,
  export: exportAPI,
  recurring: recurringAPI
}

// ========== Chat API ==========
export const chatAPI = {
  // 流式聊天（SSE）
  async streamChat(
    messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>,
    options?: { sessionId?: string; context?: any; signal?: AbortSignal }
  ): Promise<ReadableStream<Uint8Array>> {
    const url = `/api/chat/stream`
    const controller = new AbortController()
    const signal = options?.signal || controller.signal

    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(localStorage.getItem('auth_token') && {
          'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
        })
      },
      body: JSON.stringify({ messages, sessionId: options?.sessionId, context: options?.context }),
      signal
    })

    if (!response.ok || !response.body) {
      throw new Error(`SSE连接失败: ${response.status} ${response.statusText}`)
    }
    return response.body
  },

  // 增强流式聊天（支持Function Calling）
  async streamEnhancedChat(
    messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>,
    options?: { sessionId?: string; messageId?: string; signal?: AbortSignal }
  ): Promise<ReadableStream<Uint8Array>> {
    const url = `/api/chat-langchain/stream`
    const controller = new AbortController()
    const signal = options?.signal || controller.signal

    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(localStorage.getItem('auth_token') && {
          'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
        })
      },
      body: JSON.stringify({ 
        messages, 
        sessionId: options?.sessionId,
        messageId: options?.messageId // 传递messageId到后端
      }),
      signal
    })

    if (!response.ok || !response.body) {
      throw new Error(`Enhanced SSE连接失败: ${response.status} ${response.statusText}`)
    }
    return response.body
  },

  // 语音转文字
  async transcribeAudio(audioBase64: string, mimeType?: string) {
    return apiRequest<{ success: boolean; text?: string; error?: string }>('/chat/transcribe', {
      method: 'POST',
      body: JSON.stringify({ audioBase64, mimeType })
    })
  },

  // 获取可用函数列表
  async getAvailableFunctions() {
    return apiRequest<{ functions: any[] }>('/chat/functions', {
      method: 'GET'
    })
  },

  // 测试函数调用
  async testFunction(functionName: string, args: any) {
    return apiRequest<{ success: boolean; data?: any; error?: string }>('/chat/test-function', {
      method: 'POST',
      body: JSON.stringify({ functionName, args })
    })
  }
}